<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="家谱名称">
          <el-input v-model="queryParams.familyName" placeholder="请输入家谱名称" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="用户名/昵称">
          <el-input v-model="queryParams.name" placeholder="请输入用户名/昵称" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable style="width: 200px">
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['genealogy:family-user:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="familyId" label="家谱ID" prop="familyId" min-width="80" align="center" />
        <el-table-column key="familyName" label="家谱名称" prop="familyName" min-width="120" align="center" />
        <el-table-column key="username" label="用户名" prop="username" min-width="100" align="center" />
        <el-table-column key="nickname" label="昵称" prop="nickname" min-width="100" align="center" />
        <el-table-column key="mobile" label="手机号" prop="mobile" min-width="120" align="center" />
        <el-table-column key="gender" label="性别" min-width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column key="deptName" label="部门" prop="deptName" min-width="120" align="center" />
        <el-table-column key="status" label="审核状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : 'info'">
              {{ scope.row.status === 1 ? '已通过' : scope.row.status === 2 ? '已拒绝' : '待审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.status === 0" v-hasPerm="['genealogy:family-user:audit']" type="primary"
              size="small" link @click="openAuditDialog(scope.row)">
              <template #icon>
                <Check />
              </template>
              审核
            </el-button>
            <el-button v-hasPerm="['genealogy:family-user:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 审核弹窗，直接用 v-if 控制 -->
    <el-dialog v-if="auditDialogVisible" v-model="auditDialogVisible" title="审核用户加入申请" width="800px"
      :close-on-click-modal="false" @close="auditReason = ''">
      <div style="text-align:left;">
        <b>申请理由：</b><br>
        <div style="white-space:pre-line;">{{ auditDialogRow?.reason || '无' }}</div>
        <br>

        <!-- 家谱树可视化部分 -->
        <div class="family-tree-section">
          <div class="section-header">
            <h3>申请人家谱关系图</h3>
          </div>

          <!-- 用于显示申请人提交的家谱树 -->
          <div class="family-tree-container">
            <SimpleFamilyTree v-if="applicantFamilyTreeData" v-model="applicantFamilyTreeData"
              :current-user-id="currentApplicantMemberId" title="申请人家庭成员关系图" :readonly="true" />
            <div v-else class="empty-tree-message">申请人未提供家谱信息</div>
          </div>
        </div>

        <!-- 人员搜索部分 -->
        <div v-if="showPersonSearch" class="person-search-section mt-15">
          <div class="section-header">
            <h3>搜索关联人员</h3>
          </div>

          <div class="search-box">
            <el-input v-model="searchPersonKeyword" placeholder="请输入姓名/ID搜索人员" clearable class="search-input"
              @keyup.enter="searchPerson">
              <template #append>
                <el-button :loading="searchPersonLoading" @click="searchPerson">
                  <template #icon>
                    <Search />
                  </template>
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>

          <div v-if="searchPersonResults.length > 0" class="search-results mt-10">
            <el-table :data="searchPersonResults" border stripe>
              <el-table-column label="ID" prop="id" width="80" align="center" />
              <el-table-column label="姓氏" prop="firstName" width="100" align="center" />
              <el-table-column label="名字" prop="lastName" width="100" align="center" />
              <el-table-column label="性别" width="80" align="center">
                <template #default="scope">
                  {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
                </template>
              </el-table-column>
              <el-table-column label="家谱ID" prop="familyId" width="100" align="center" />
              <el-table-column label="家谱名称" prop="familyName" min-width="120" align="center" />
              <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                  <el-button type="primary" link @click="selectPerson(scope.row)">
                    选择
                  </el-button>
                  <el-button :type="lastViewedPersonId === scope.row.id ? 'success' : 'info'" link
                    @click="viewPersonFamilyTree(scope.row)">
                    查看家谱
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div v-if="selectedPerson" class="selected-person mt-10">
            <el-alert type="success" :title="`已选择关联人员: ${selectedPerson.firstName} ${selectedPerson.lastName}`"
              :closable="false" show-icon />
          </div>
        </div>

        <!-- 关联人员家谱树展示部分 -->
        <div v-if="showRelatedPersonTree" class="family-tree-section mt-15">
          <div class="section-header">
            <h3>关联人员家谱关系图 - {{ currentViewingPerson ? `${currentViewingPerson.firstName}
              ${currentViewingPerson.lastName}` :
              '' }}</h3>
            <el-button type="primary" size="small" @click="hideRelatedPersonTree">
              返回搜索
            </el-button>
          </div>

          <div class="family-tree-container">
            <SimpleFamilyTreeS v-if="relatedPersonTreeData" v-model="relatedPersonTreeData"
              :current-user-id="currentRelatedPersonId" title="关联人员家庭成员关系图" :readonly="true" />
            <div v-else class="empty-tree-message">正在加载关联人员家谱信息...</div>
          </div>
        </div>

        <el-form>
          <el-form-item label="审核理由" required>
            <el-input type="textarea" v-model="auditReason" :rows="3" maxlength="200" show-word-limit
              placeholder="请输入审核理由（必填）" />
          </el-form-item>
          <el-form-item label="类型选择" required>
            <el-radio-group v-model="auditType">
              <el-radio :label="1">消耗自己的指标</el-radio>
              <el-radio :label="2">用户自己购买指标</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleAuditPass">通过</el-button>
        <el-button type="danger" @click="handleAuditReject">拒绝</el-button>
        <el-button @click="auditDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "FamilyUser",
  inheritAttrs: false,
});
import FamilyUserAPI from "@/api/genealogy/family-user.api";
import PersonAPI from "@/api/genealogy/person.api";
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus';
import { Search, Refresh, Delete, Check, Close } from '@element-plus/icons-vue';
import SimpleFamilyTreeS from "@/components/FamilyTree/SimpleFamilyTreeS.vue";

const queryFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<FamilyUserPageQuery>({
  pageNum: 1,
  pageSize: 10,
  familyName: '',
  name: '',
  status: undefined
});

// 家谱用户加入表格数据
const pageData = ref<FamilyUserPageVO[]>([]);

const auditDialogVisible = ref(false);
const auditDialogRow = ref<any>(null);
const auditReason = ref('');
const auditType = ref(1); // 1: 消耗自己的指标, 2: 用户自己购买指标

// 家谱树相关变量
const familyId = ref(''); // 当前审核的家谱ID
const applicantFamilyTreeData = ref(null); // 申请人的家谱树
const currentApplicantMemberId = ref(''); // 申请人树中当前用户ID

// 人员搜索相关变量
const searchPersonKeyword = ref(''); // 搜索关键词
const searchPersonResults = ref([]); // 搜索结果
const searchPersonLoading = ref(false); // 搜索加载状态
const selectedPerson = ref(null); // 选中的人员
const showPersonSearch = ref(true); // 是否显示人员搜索

// 关联人员家谱树相关变量
const showRelatedPersonTree = ref(false); // 是否显示关联人员家谱树
const relatedPersonTreeData = ref(null); // 关联人员的家谱树数据
const currentRelatedPersonId = ref(''); // 关联人员树中当前用户ID
const relatedPersonTreeLoading = ref(false); // 关联人员树加载状态
const lastViewedPersonId = ref(null); // 记录最后查看的人员ID
const currentViewingPerson = ref(null); // 记录当前正在查看的人员


interface FamilyUserPageQuery {
  pageNum: number;
  pageSize: number;
  familyName?: string;
  name?: string;
  status?: number;
}

interface FamilyUserPageVO {
  id: string;
  familyId: string;
  familyName: string;
  userId: string;
  status: number;
  isDeleted: number;
  createTime: string;
  updateTime: string;
  createBy: string;
  updateBy: string | null;
  username: string;
  nickname: string;
  areaCode: string;
  mobile: string;
  gender: number;
  avatar: string | null;
  deptName: string;
  roleNames: string;
  email: string | null;
  mergerName: string;
  address: string | null;
}

/** 查询家谱用户加入 */
function handleQuery() {
  loading.value = true;
  // 清空之前的数据，避免数据混合
  pageData.value = [];
  FamilyUserAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置家谱用户加入查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 删除家谱用户加入 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      FamilyUserAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 审核家谱用户加入 */
function openAuditDialog(row: any) {

  auditDialogRow.value = row;
  auditReason.value = '';
  auditType.value = 1; // 默认选择消耗自己的指标
  auditDialogVisible.value = true;

  // 重置搜索相关状态
  searchPersonKeyword.value = '';
  searchPersonResults.value = [];
  selectedPerson.value = null;
  showPersonSearch.value = true;
  showRelatedPersonTree.value = false;
  relatedPersonTreeData.value = null;
  lastViewedPersonId.value = null;
  currentViewingPerson.value = null;

  // 设置当前家谱ID
  familyId.value = row.familyId;

  // 使用loadFamilyDataById函数获取家谱树数据
  loading.value = true;
  loadFamilyDataById(row.id)
    .then((familyData) => {
      applicantFamilyTreeData.value = familyData;
    })
    .catch((error) => {
      ElMessage.error('获取家谱树数据失败');
      applicantFamilyTreeData.value = null;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 根据ID加载家谱数据
function loadFamilyDataById(id) {
  return new Promise((resolve, reject) => {
    FamilyUserAPI.detail(id)
      .then((data) => {
        let familyData = null;
        try {
          if (data.familyData && typeof data.familyData === 'string') {
            familyData = JSON.parse(data.familyData);
          } else {
            familyData = data.familyData || null;
          }
          resolve(familyData);
        } catch (error) {
          console.error('解析家谱树数据失败:', error);
          reject(error);
        }
      })
      .catch((error) => {
        console.error('获取家谱树数据失败:', error);
        reject(error);
      });
  });
}

// 搜索人员
function searchPerson() {

  searchPersonLoading.value = true;
  searchPersonResults.value = [];

  // 使用PersonAPI.getPage替代searchGlobal
  const searchParams = {
    pageNum: 1,
    pageSize: 10,
    lastName: searchPersonKeyword.value,
    familyId: familyId.value
  };

  PersonAPI.getPage(searchParams)
    .then((data) => {
      searchPersonResults.value = data.list || [];
      if (searchPersonResults.value.length === 0) {
        ElMessage.info('未找到匹配的人员');
      }
    })
    .catch((error) => {
      console.error('搜索人员失败:', error);
      ElMessage.error('搜索人员失败');
    })
    .finally(() => {
      searchPersonLoading.value = false;
    });
}

// 选择人员
function selectPerson(person) {
  selectedPerson.value = person;
  // 选择人员后隐藏搜索结果列表
  searchPersonResults.value = [];
  ElMessage.success(`已选择: ${person.firstName} ${person.lastName}`);
}

// 查看人员家谱树
function viewPersonFamilyTree(person) {
  currentRelatedPersonId.value = person.id;
  relatedPersonTreeData.value = null;
  showPersonSearch.value = false;
  showRelatedPersonTree.value = true;
  relatedPersonTreeLoading.value = true;

  // 加载关联人员家谱树数据
  PersonAPI.getTreeDataForFour(person.id)
    .then((data) => {
      relatedPersonTreeData.value = data;
    })
    .catch((error) => {
      console.error('获取关联人员家谱树数据失败:', error);
      ElMessage.error('获取关联人员家谱树数据失败');
    })
    .finally(() => {
      relatedPersonTreeLoading.value = false;
    });

  // 记录最后查看的人员ID
  lastViewedPersonId.value = person.id;
  currentViewingPerson.value = person;
}

// 隐藏关联人员家谱树，返回搜索界面
function hideRelatedPersonTree() {
  showRelatedPersonTree.value = false;
  showPersonSearch.value = true;
  // 不清除lastViewedPersonId，这样返回后仍能看到上次查看的是哪个成员
}

function handleAuditPass() {
  const row = auditDialogRow.value;
  if (!auditReason.value.trim()) {
    ElMessage.warning('请输入通过理由');
    return;
  }

  // 构建审核数据,包含节点连接信息
  const auditData = {
    status: 1,
    reason: auditReason.value,
    auditType: auditType.value,
    familyData: applicantFamilyTreeData.value // 添加家谱树数据
  };

  // 人员搜索关联方式
  if (selectedPerson.value) {
    auditData['connectionInfo'] = {
      personId: selectedPerson.value.id,
      familyId: selectedPerson.value.familyId
    };
  } else {
    ElMessage.warning('请先选择关联人员');
    return;
  }

  auditDialogVisible.value = false;
  loading.value = true;

  FamilyUserAPI.update(row.id, auditData)
    .then(() => {
      ElMessage.success('审核通过成功');
      handleQuery();
    })
    .finally(() => (loading.value = false));
}

function handleAuditReject() {
  const row = auditDialogRow.value;
  if (!auditReason.value.trim()) {
    ElMessage.warning('请输入拒绝理由');
    return;
  }
  auditDialogVisible.value = false;
  loading.value = true;
  const auditData = {
    status: 2,
    reason: auditReason.value,
    auditType: auditType.value,
    familyData: applicantFamilyTreeData.value // 添加家谱树数据
  };

  // 即使是拒绝，也保存连接信息，以便将来可能的重新审核
  if (selectedPerson.value) {
    auditData['connectionInfo'] = {
      personId: selectedPerson.value.id,
      familyId: selectedPerson.value.familyId
    };
  }

  FamilyUserAPI.update(row.id, auditData)
    .then(() => {
      ElMessage.success('审核拒绝成功');
      handleQuery();
    })
    .finally(() => (loading.value = false));
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.family-tree-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 16px;
}

.family-tree-container {
  width: 100%;
  height: 400px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #fff;
  overflow: auto;
  padding: 10px;
}

.empty-tree-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.connection-section {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.connection-info {
  margin-top: 10px;
}

.mt-10 {
  margin-top: 10px;
}

.mt-15 {
  margin-top: 15px;
}

.ml-10 {
  margin-left: 10px;
}

.person-search-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-box {
  margin-bottom: 10px;
}

.search-input {
  width: 100%;
}

.search-results {
  margin-top: 10px;
}

.selected-person {
  margin-top: 10px;
}
</style>
